package com.spi.controller;

import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

@RestController
@RequestMapping("pdf03")
public class PdfController03 {

    @CrossOrigin(origins = "http://localhost:63342")
    @RequestMapping("test01")
    public String test01(){
        System.out.println("进来了。。。。");
        try {
            String filePath = "D:\\555\\pdftest\\777.pdf";
            byte[] fileContent = Files.readAllBytes(Paths.get(filePath));
            String base64String = Base64.getEncoder().encodeToString(fileContent);
            return base64String;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    @CrossOrigin(origins = "http://localhost:63342")
    @GetMapping("/test01/chunk")
    public ResponseEntity<byte[]> getPdfChunk(@RequestParam("start") long start, @RequestParam("end") long end) {
        System.out.println(end);
        try (RandomAccessFile file = new RandomAccessFile("D:\\555\\pdftest\\MIC老师最新面试文档.pdf", "r");
             FileChannel channel = file.getChannel()) {

            long fileSize = file.length();
            if (end > fileSize - 1) {
                end = fileSize - 1;
            }

            ByteBuffer buffer = ByteBuffer.allocate((int) (end - start + 1));
            channel.read(buffer, start);
            buffer.flip();

            byte[] chunk = buffer.array();
            //String base64Chunk = Base64.getEncoder().encodeToString(chunk);

            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Range", "bytes " + start + "-" + end + "/" + fileSize);
            headers.add("Accept-Ranges", "bytes");
            headers.add("Content-Type", "application/pdf");
            headers.add("Access-Control-Expose-Headers", "Content-Range, Accept-Ranges"); //跨域问题，开放Content-Range、Accept-Ranges响应头
            System.out.println("Content-Range: bytes " + start + "-" + end + "/" + fileSize);
            if (end == fileSize - 1) {
                return new ResponseEntity<>(chunk, headers, HttpStatus.OK);
            } else {
                return new ResponseEntity<>(chunk, headers, HttpStatus.PARTIAL_CONTENT);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
